#!/usr/bin/env python

'''this is a demo module about calling taobao api'''

import urllib
import urllib2
import time
import md5
import base64
import json

resultFormat = 'json'
version = '2.0'

def _sign(param, sercetCode):
    '''generate sign'''
    src = sercetCode + ''.join(["%s%s" % (k, v) for k, v in sorted(param.items())])
    return md5.new(src).hexdigest().upper()

def getResult(paramDict, app_secret):
    '''call taobao api and get result'''
    paramDict['format'] = resultFormat
    paramDict['v'] = version
    paramDict['timestamp'] = time.strftime('%Y-%m-%d %X', time.localtime())
    paramDict['sign'] = _sign(paramDict, app_secret)
    form_data = urllib.urlencode(paramDict)
    urlopen = urllib2.urlopen('http://gw.api.tbsandbox.com/router/rest', form_data)
    rsp = urlopen.read()
    rsp = rsp.decode('UTF-8')
    rsp = json.loads(rsp)
    return rsp

if __name__ == '__main__':
    paramDict = {
        'app_key':'12034368',
        'method':'taobao.user.get',
        'fields':'nick,sex,buyer_credit,seller_credit,location.city,location.state,location.country,created,last_visit',
        'nick':'alipublic12'
    }
    app_secret = 'f72fdd1f8d874bf7f4f387b10a8cb576'
    print getResult(paramDict, app_secret)
#    print rsp
#    print rsp['user_get_response']['user']['created']